#include"Protocol.hpp"
#include"sock.hpp"
#include<pthread.h>
void Usage(string str )
{
  cout<<"Usage: "<<str<<" port"<<endl;
}

void* Hander(void* args)//长服务
{
  int  sock =*((int*)args);
  delete (int*)args;
  pthread_detach(pthread_self());
  //业务逻辑
  //1.读取请求
  //2.分析请求
  //3.计算结果
  //4.构建响应，并进行返回
  //5.关闭连接
  while(1){
    char buffer[1024]={0};
    ssize_t s = read(sock,buffer,sizeof(buffer)-1);
    if(s>0)
    { 
      buffer[s]='\0';
      request_t req;
      string str=buffer;
      cout<<"get a new resquest: "<<str<<endl;
      DeserializeRequest(str,req); //反序列化
      response_t resp={0,0};
      switch(req.op)
      {
        case '+':resp.result = req.x+req.y; break;
        case '-':resp.result = req.x-req.y; break;
        case '*':resp.result = req.x*req.y; break;
        case '/':if(req.y==0) resp.code=-1;//代表除0
                   else resp.result = req.x/req.y;
                   break;
        case '%':if(req.y==0) resp.code=-2;
                   else resp.result = req.x%req.y;
                   break;
        default: resp.code = -3;
                 break;
      }   
     string send_string =  SerializeRespon(resp);//序列化发送

      write(sock,send_string.c_str(),send_string.size());        
    }

    cout<<"服务结束"<<endl;

  }
}
  int main(int argc,char* argv[])
  {
    if(argc!=2)
    {
      Usage(argv[0]);
      exit(1);
    }
    uint16_t port = atoi(argv[1]);
    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock,port);
    Sock::Listen(listen_sock);

    while(true)
    {
      int sock =  Sock::Accept(listen_sock);
      if(sock>=0)
      {
        cout<<"get a new link..."<<endl;
        int* pram = new int(sock);
        pthread_t tid;
        pthread_create(&tid,nullptr,Hander,pram);
      }
    }

    return 0;
  }
